package net.piggy.test;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFile {


    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\smart\\Pictures\\picture");
        FileOutputStream fos = new FileOutputStream("C:\\Users\\smart\\Pictures\\111.zip");
        ZipOutputStream zos = new ZipOutputStream(fos);
        zip(file, "", zos);
        zos.close();
        fos.close();
    }

    public static void zip(File file, String fileName, ZipOutputStream zos) throws IOException {
        if(file.isDirectory()){
            File[] files = file.listFiles();
            if(files!=null){
                for (File f : files){
                    if(f.isDirectory()){
                        zos.putNextEntry(new ZipEntry(fileName+f.getName()+"/"));
                        zos.closeEntry();
                        zip(f, fileName+f.getName()+"/", zos);
                    }else{
                        FileInputStream fis = new FileInputStream(f);
                        ZipEntry zipEntry = new ZipEntry(fileName+f.getName());
                        zos.putNextEntry(zipEntry);
                        byte[] bytes = new byte[1024];
                        int length;
                        while ((length = fis.read(bytes))>=0){
                            zos.write(bytes, 0, length);
                        }
                        zos.closeEntry();
                        fis.close();

                    }
                }
            }
        }
    }
}
